<?php
namespace app;

use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param  Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request   $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        // 其他错误交给系统处理
        return parent::render($request, $e);
    }

    /**
     * 收集调试模式异常数据
     * @access protected
     * @param Throwable $exception
     * @return array
     */
    protected function getDebugMsg(Throwable $exception): array
    {
        // 调试模式，获取详细的错误信息
        $traces        = [];
        $nextException = $exception;

        do {
            $traces[] = [
                'name'    => $nextException::class,
                'file'    => $nextException->getFile(),
                'line'    => $nextException->getLine(),
                'code'    => $this->getCode($nextException),
                'message' => $this->getMessage($nextException),
                'trace'   => $this->app->request->isAjax() ? $nextException->getTraceAsString() : $nextException->getTrace(),
                'source'  => $this->getSourceCode($nextException),
            ];
        } while ($nextException = $nextException->getPrevious());
        
        return [
            'code'    => $this->getCode($exception),
            'message' => $this->getMessage($exception),
            'traces'  => $traces,
            'datas'   => $this->getExtendData($exception),
            'tables'  => [
                'GET Data'            => $this->app->request->get(),
                'POST Data'           => $this->app->request->post(),
                'Files'               => $this->app->request->file(),
                'Cookies'             => $this->app->request->cookie(),
                'Session'             => $this->app->exists('session') ? $this->app->session->all() : [],
                'Server/Request Data' => $this->app->request->server(),
            ],
        ];
    }
}
